//
//  WKPersonalInfoController.m
//  WeKeTang
//
//  Created by ichina on 2017/9/6.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKPersonalInfoController.h"
#import "ScottAlertController.h"
#import "WKNickNameController.h"
#import "WKNetworkTools.h"
#import "WKLoginHandel.h"
#import "WKUniversal.h"
#import "NSString+KZExtension.h"

@interface WKPersonalInfoController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>

@property (nonatomic, strong) NSArray *gradeList;

@end

@implementation WKPersonalInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadInfoData];
    
    [self setupUI];
    
    
}
- (void)loadInfoData{
    
    __weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *SESSID = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSString *mac = [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"personinfo" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:SESSID forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        [weakSelf showCustomAlertMessage:@"网络错误"];
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *body =dict[@"body"];
        NSString *avatar = body[@"avatar"];
        NSString *grade = body[@"grade"];
        NSString *nickname = body[@"nickname"];
        NSData *locData = [WKUniversal getImgData];
        UIImage *image = [UIImage imageWithData:locData];
        if (locData == nil) {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:avatar]];
            UIImage *image = [UIImage imageWithData:data];
            [weakSelf.imgAvader setImage:image forState:UIControlStateNormal];
        }else{
            [weakSelf.imgAvader setImage:image forState:UIControlStateNormal];
        }
        [weakSelf.nickName setTitle:nickname forState:UIControlStateNormal];
        weakSelf.grade.text = [self exchangeGradeString:grade];
        NSLog(@"获取个人信息：%@",dict);
    }];
}
- (void)setupUI{
    
    self.navgationBar.barTintColor = RGBColor(40, 188, 203);
    self.statusbar.backgroundColor = RGBColor(40, 188, 203);
    self.view.backgroundColor = RGBColor(245, 245, 245);
    [self setLeftButtonWithImage:@"icon_return_white" highlightedImage:@"icon_return_white" target:self action:@selector(backAction)];
    [self middleTitleColor:[UIColor whiteColor]];
    [self setLeftButtonWithImage:@"" highlightedImage:@"" target:self action:@selector(backAction)];
    self.navItem.title = @"个人资料";
    
    self.imgAvader.layer.cornerRadius = 14;
    self.imgAvader.layer.masksToBounds = YES;
    self.imgAvader.userInteractionEnabled = YES;
    UITapGestureRecognizer *imgAvaderTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnAvaderAction:)];
    [self.imgAvader addGestureRecognizer:imgAvaderTap];
    self.nickName.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.grade.userInteractionEnabled = YES;
    UITapGestureRecognizer *gradeTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gradeTapAction:)];
    [self.grade addGestureRecognizer:gradeTap];
    
}
- (void)backAction{
    
    if (self.backBlock) {
        
        self.backBlock();
    }
    [super backAction];
}
#pragma mark - 头像
- (IBAction)btnAvaderAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"userinfo_avatar"];
    __weak typeof(self) weakSelf = self;
    ScottAlertView *alertView = [ScottAlertView alertViewWithTitle:@"提示" message:@"请选择获取照片方式 "];
    [alertView addAction:[ScottAlertAction actionWithTitle:@"拍照" style:ScottAlertActionStyleDefault handler:^(ScottAlertAction *action) {
        //拍照
        [weakSelf takePhotoAntion];
    }]];
    [alertView addAction:[ScottAlertAction actionWithTitle:@"相册" style:ScottAlertActionStyleDefault handler:^(ScottAlertAction *action) {
        //相册
        [weakSelf selectPhotoAntion];
    }]];
    [alertView addAction:[ScottAlertAction actionWithTitle:@"取消" style:ScottAlertActionStyleCancel handler:^(ScottAlertAction *action) {

    }]];
    ScottAlertViewController *alertController = [ScottAlertViewController alertControllerWithAlertView:alertView preferredStyle:ScottAlertControllerStyleActionSheet];
    alertController.tapBackgroundDismissEnable = YES;
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 昵称
- (IBAction)nickNameAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"userinfo_nickname"];
    __weak typeof(self) weakSelf = self;
    WKNickNameController *nickNameVC = [[WKNickNameController alloc]init];
    nickNameVC.nickName = self.nickName.titleLabel.text;
    nickNameVC.block = ^(NSString *nickName) {
        [self.nickName setTitle:nickName forState:UIControlStateNormal];
        NSLog(@"昵称%@",nickName);
        //修改昵称接口
        [weakSelf updateNickNameWithName:nickName];
    };
    [self.navigationController pushViewController:nickNameVC animated:YES];
}
#pragma mark - 修改昵称接口
- (void)updateNickNameWithName:(NSString*)name{
    
    __weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *SESSID = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSString *mac = [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"updateinfo" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:SESSID forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:name forKey:@"nickname"];
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"修改中..." completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"修改昵称： %@",dict);
        NSDictionary *head = dict[@"head"];
        NSString *statuscode = head[@"statuscode"];
        if ([statuscode intValue] == 100) {
            
            [self showCustomAlertMessage:@"修改成功!!"];
            [weakSelf.nickName setTitle:name forState:UIControlStateNormal];
        }else{
            [self showCustomAlertMessage:@"修改失败"];
        }
    }];
    
}
#pragma mark - 年级
- (void)gradeTapAction:(UITapGestureRecognizer*)tap{
    [MobClick profileSignInWithPUID:@"userinfo_grade"];
    self.gradeList = @[@"小学",@"初一",@"初二",@"初三",@"高一",@"高二",@"高三"];
    UIActionSheet * sheet = [[UIActionSheet alloc] initWithTitle:@"年级" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"小学" otherButtonTitles:@"初一",@"初二", @"初三", @"高一",@"高二",@"高三", nil];
    
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    NSLog(@"%ld",buttonIndex);
    if (buttonIndex>6) {
        
        [actionSheet removeFromSuperview];
    }else{
        self.grade.text = self.gradeList[buttonIndex];
        //修改年级接口
        [self updateGradeDataWithGradeString:self.grade.text];
    }
}
#pragma mark -修改年级接口
- (void)updateGradeDataWithGradeString:(NSString*)gradeString{
    
    __weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *SESSID = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSString *mac = [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"personinfo" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:SESSID forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:gradeString forKey:@"grade"];
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"修改年级：%@",dict);
        NSDictionary *head = dict[@"head"];
        NSString *statuscode = head[@"statuscode"];
        if ([statuscode intValue] == 100) {
             [weakSelf showCustomAlertMessage:@"修改成功!!"];
        }else{
            [weakSelf showCustomAlertMessage:@"修改失败"];
        }
    }];
    
    
}
#pragma mark - 拍照
- (void)takePhotoAntion{
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
    ipc.delegate = self;
    ipc.allowsEditing = YES;
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        [ipc setSourceType:UIImagePickerControllerSourceTypeCamera];
        [self presentViewController:ipc animated:YES completion:Nil];
        
    }else{
        
        [self showCustomAlertMessage:@"您的设备没有安装摄像头"];
    }
}
#pragma mark - 相册选择
- (void)selectPhotoAntion{
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
    ipc.delegate = self;
    ipc.allowsEditing = YES;
    [ipc setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
    [self presentViewController:ipc animated:YES completion:Nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [self dismissViewControllerAnimated:YES completion:Nil];
    
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.6);
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    
    NSString *imageName = @"clip_temp.jpg";
    [img setAccessibilityIdentifier:imageName];
    NSLog(@"图片名字是:%@",img.accessibilityIdentifier);
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:userid forKey:@"userid"];
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer  serializer];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger POST:@"http://www.dezhi.com/andriodwk/save-avatar" parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSLog(@"formData%@",formData);
        [formData appendPartWithFileData:data name:@"uploadedfile" fileName:@"clip_temp.jpg" mimeType:@"image/jpg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"上传头像%@",responseObject[@"head"]);

        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *msg = [self replaceUnicode:str];
        NSLog(@"上传头像成功:%@",msg);
        [self.imgAvader setImage:img forState:UIControlStateNormal];
        NSData *data = UIImagePNGRepresentation(img);
        //保存头像到本地
        [WKUniversal saveImgData:data];
//        self.imgAvader.imageView.contentMode = UIViewContentModeScaleAspectFill;
//        self.imgAvader.imageView.clipsToBounds =YES;
        [self showCustomAlertMessage:@"头像上传成功！"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showCustomAlertMessage:@"上传头像失败"];
        NSLog(@"上传头像失败:%@",error);
    }];
}

- (NSString *)exchangeGradeString:(NSString*)gradeString{
    
    if ([gradeString isEqualToString:@"1036"]) {
        return @"小学";
    }else if ([gradeString isEqualToString:@"1037"]){
        return @"初一";
    }else if ([gradeString isEqualToString:@"1038"]){
        return @"初二";
    }else if ([gradeString isEqualToString:@"1039"]){
        return @"初三";
    }else if ([gradeString isEqualToString:@"1040"]){
        return @"高一";
    }else if ([gradeString isEqualToString:@"1041"]){
        return @"高二";
    }else if ([gradeString isEqualToString:@"1042"]){
        return @"高三";
    }
    return @"初一";
}
-(NSString *)replaceUnicode:(NSString *)unicodeStr{
    
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
